package com.itheima.reggie.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            //生成随机的4位验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            //调用阿里云提供的短信服务API完成发送短信
//            AliyunSmsUtil.sendSms(phone,code);
            log.info(code.toString());
            //需要将生成的验证码保存到Session
            session.setAttribute("phone",phone);
            session.setAttribute("code",code);
            return R.success("手机验证码短信发送成功");
        }
        return R.error("手机号不存在");
    }
    @PostMapping("/login")
    public R<User> login(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        Integer code =user.getCode();

        String phoneSession = (String) session.getAttribute("phone");
        Integer codeSession = (Integer) session.getAttribute("code");

        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        if(code.equals(codeSession)){
            if(phone.equals(phoneSession)){
                LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
                qw.eq(User::getPhone, phone);
                User user1 = userService.getOne(qw);
                if (user1 == null) {
                    //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                    user1 = new User();
                    user1.setPhone(phone);
                    user1.setStatus(1);
                    userService.save(user1);
                }
                session.setAttribute("user",user1);
                return R.success(user1);
            }else{
                return R.error("号码改变!");
            }
        }
        return R.error("验证码不正确确!");
    }
 }
